package com.lcq.qiaoqiaosplash.sdk;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Interpolator;
import android.widget.ImageView;

public abstract class QiaoQiaoSplashActivity extends Activity {
    protected ImageView img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int splashImgId = getResources().getIdentifier("splash_img", "drawable", getPackageName());
        if (splashImgId <= 0) {
            onQiaoQiaoSplashEnd();
            return;
        }
        if (!isTaskRoot()) {//处理应用切到后台，再切回来，重复显示闪屏页的问题
            final Intent intent = getIntent();
            final String intentAction = intent.getAction();
            if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && intentAction != null
                    && intentAction.equals(Intent.ACTION_MAIN)) {
                finish();
                return;
            }
        }
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(getResources().getIdentifier("splash_img", "layout", getPackageName()));

        //加载闪屏图片
        img = findViewById(getResources().getIdentifier("img", "id", getPackageName()));
        img.setImageResource(splashImgId);

        startAnim();
    }

    public abstract void onQiaoQiaoSplashEnd();

    public void startAnim() {
        ValueAnimator va = ValueAnimator.ofFloat(0, 1, 1, 0);
        va.addUpdateListener(animation -> {
            float params = (float) animation.getAnimatedValue();
            img.setAlpha(params);
        });
        va.setInterpolator((Interpolator) input -> input);
        va.setDuration(3000);
        va.setRepeatCount(0);
        va.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                onQiaoQiaoSplashEnd();
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
        va.start();
    }

    @Override
    public void onBackPressed() {
        //处理闪屏页按返回键不finish
    }
}
